import { constantRoutes } from '@/router'
import { getAdminMenuList, getUserMenuList } from '@/api/system/menu'
import { flatMenu } from '../menu'
import Layout from '@/layout'

const state = {
  routes: [],
  addRoutes: [],
  priv: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PRIV: (state, priv) => {
    state.priv = priv
  }
}

const actions = {
  async generateRoutes({ commit }, info) {
    let menu = null
    if (info.isAdmin) {
      menu = await getAdminMenuList()
    } else {
      menu = await getUserMenuList({ searchForm: { roles: info.roles }})
    }
    const route = flatMenu(menu.data.listLine, {})
    return new Promise(resolve => {
      commit('SET_PRIV', menu.data.priv ? menu.data.priv : [])
      const routers = generator(route)
      commit('SET_ROUTES', routers)
      resolve(route)
    })
  }
}

const generator = (routerMap, parent) => {
  return routerMap.map(router => {
    delete router['menuId']
    delete router['parentMenu']

    if (router.component === 'Layout') {
      router.component = Layout
    } else {
      router.component = loadView(router.component)
    }

    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!router.path.startsWith('http')) {
      router.path = router.path.replace('//', '/')
    }
    if (router.children && router.children.length > 0) {
      router.children = generator(router.children, router)
    }
    return router
  })
}

const loadView = (view) => {
  // webpack4 不支持变量方式的动态 import ，需要使用 require()
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
